// request.js
import axios from 'axios'
import store from '../store/index.js'
import { ACTION_CHANGE_LOADING } from '../store/actioncreaters'
import url from '../config.js'
/** **** request拦截器==>对请求参数做处理 ******/
axios.interceptors.request.use(
  (config) => {
    // 加载
    store.dispatch(ACTION_CHANGE_LOADING(true))
    let value = sessionStorage.getItem('token') || '123'
    if (value) config.headers.Authorization = value
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
/** **** respone拦截器==>对响应做处理 ******/
axios.interceptors.response.use(
  (response) => {
    store.dispatch(ACTION_CHANGE_LOADING(false))
    return response
  },
  (error) => {
    // 错误提醒

    store.dispatch(ACTION_CHANGE_LOADING(false))
    const { status } = error.response
    if (status === 401) {
      // 清除token
      sessionStorage.clear()
      window.location.href = url.homeurl
    }
    if (status === 404) {
      window.location.href = url.homeurl
    }
    // 页面跳转
    //router.push('/login')

    return Promise.reject(error)
  }
)
export default axios
